//
//  RosterViewController.m
//  XMPPMessage
//
//  Created by 刘永杰 on 15/11/21.
//  Copyright © 2015年 刘永杰. All rights reserved.
//

#import "RosterViewController.h"
#import "XMPPManager.h"
#import "MessageViewController.h"
@interface RosterViewController ()<XMPPStreamDelegate, XMPPRosterDelegate, UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;

@end

@implementation RosterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = [NSMutableArray array];
    //XMPPRoster是管理用户的类
    [[XMPPManager defaultManager].XMPPRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    // Do any additional setup after loading the view.
}

- (void)xmppRoster:(XMPPRoster *)sender didReceiveRosterItem:(DDXMLElement *)item
{
    NSLog(@"获取到好友");
    
    if ([[[item attributeForName:@"subscription"] stringValue] isEqualToString:@"both"]) {
        
        //获取item里面的jid节点的数据
        NSString *jidStr = [[item attributeForName:@"jid"] stringValue];
        //通过在item里面获取的数据  初始化一个XMPPJID
        XMPPJID *jid = [XMPPJID jidWithString:jidStr];
        //把这个jid放到数据源数组里面
        [self.dataArray addObject:jid];
        
        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)xmppRosterDidBeginPopulating:(XMPPRoster *)sender
{
    NSLog(@"开始获取好友");
    
}

- (void)xmppRosterDidEndPopulating:(XMPPRoster *)sender
{
    NSLog(@"结束获取好友");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rostercell" forIndexPath:indexPath];
    XMPPJID *jid = self.dataArray[indexPath.row];
    cell.textLabel.text = jid.user;
    NSLog(@"%@", jid.user);
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageViewController *messageVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MessageVC"];
    messageVC.toJID = self.dataArray[indexPath.row];
    
    [self presentViewController:messageVC animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
